package com.itheima.boottlias.aop;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.itheima.boottlias.domain.pojo.OperateLog;
import com.itheima.boottlias.mapper.OperateLogMapper;
import com.itheima.boottlias.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-07-18 12:01
 */
@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.boottlias.annotation.LogAnnotation)")
    public Object insertLogMethod(ProceedingJoinPoint pjp) throws Throwable {
        OperateLog operateLog = new OperateLog();

        //操作人ID
        operateLog.setOperateEmpId(ThreadLocalUtils.get());
        // 操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        // 全类名
        String className = pjp.getTarget().getClass().getName();
        operateLog.setClassName(className);
        // 方法名
        String methodName = pjp.getSignature().getName();
        operateLog.setMethodName(methodName);
        // 参数
        Object[] args = pjp.getArgs();
        String methodParams = "";
        if(ArrayUtil.isNotEmpty(args)) {
            methodParams = Arrays.asList(args).toString();
        }
        operateLog.setMethodParams(methodParams);
        //执行时长
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        operateLog.setCostTime(end-start);
        // 返回值
        operateLog.setReturnValue(JSONUtil.toJsonStr(result));
        operateLogMapper.insert(operateLog);
        return result;
    }

}
